package com.osdp.gateway.service.impl;

import com.osdp.gateway.service.IDynamicRouteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

/**
 * 提供动态路由的基础方法，可通过获取bean操作该类的方法。该类提供新增路由、更新路由、删除路由，然后实现发布的功能。
 * @Date 2021-5-11
 *
 */
@Service
public class DynamicRouteServiceImpl implements IDynamicRouteService, ApplicationEventPublisherAware {

    @Autowired
    private RouteDefinitionWriter routeDefinitionWriter;

    private ApplicationEventPublisher applicationEventPublisher;

    /**
     * 增加动态路由
     * @param routeDefinition
     * @return "success" String
     */
    @Override
    public String add(RouteDefinition routeDefinition) {
        routeDefinitionWriter.save(Mono.just(routeDefinition)).subscribe();
        applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
        return "success";
    }

    /**
     * 更新路由信息
     * @param routeDefinition
     * @return
     */
    @Override
    public String update(RouteDefinition routeDefinition) {
        try {
            routeDefinitionWriter.delete(Mono.just(routeDefinition.getId()));
        }catch (Exception e){
            return "update fail,not find route  routeId: "+routeDefinition.getId();
        }
        try{
            routeDefinitionWriter.save(Mono.just(routeDefinition)).subscribe();
            applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
            return "success";
        }catch (Exception e){
            return "update route fail";
        }
    }

    /**
     * 删除路由
     * @param serviceId
     * @return
     */
    @Override
    public String delete(String serviceId) {
        try {
            routeDefinitionWriter.delete(Mono.just(serviceId));
            return "delete success";
        }catch (Exception e){
            return "update fail,not find route  routeId: "+serviceId;
        }
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }
}
